#include<signal.h>
#include<iostream>
#include<cerrno>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>

using namespace std;

void get_signal(int signo)
{
    cout << "Receive a signal: " << signo << endl;
}

void test_1() //signal函数
{
    signal(2, get_signal);

    while(true)
    {
        cout << "This is a process:" << getpid() << endl;
        sleep(1);
    }
}

void test_2() //kill函数
{
    int cnt = 5;
    while(true)
    {
        cnt--;
        cout << "Running" << endl;
        sleep(1);
        if(cnt == 0)
        {
            kill(getpid(), 9); //直接杀进程
        }
    }
}

void test_3() //abort函数
{
    pid_t pid = fork();
    int cnt = 5;
    if(pid == 0)
    {
        while(true)
        {
            cout << "Running" << endl;
            if(cnt == 0)
            {
                cout << "Receive abort signal." << endl;
                abort();
            }
            cnt--;
            sleep(1);
        }
    }
    waitpid(pid, nullptr, 0);
}

int main()
{
    //test_1();
    //test_2();    
    test_3();

    return 0;
}
